﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Management;
using System.Windows.Forms;
using com.hebg3.app;
using com.hebg3.app.model;
using com.hebg3.app.zip;
using com.hebg3.cmd;
using com.hebg3.ui;
using com.hebg3.usb.watcher.impl;
using DevComponents.DotNetBar;
using com.hebg3;
using com.hebg3.app.security;
using NetDragon.LSData.AndroidDevice;
using com.hebg3.util;
using System.Diagnostics;
using System.Threading;

namespace AppKey {
  /// <summary>主窗体</summary>
  public partial class FormMain : Office2007Form {
    //持有进度条窗口
    private FormProgress formProgress = null;
    //定义进度条步进委托
    private delegate bool IncreaseHandle(int nValue);
    //定义切换label委托
    private delegate void SetLable(String label);

    private SetLable setLable = null;

    private IncreaseHandle myIncrease = null;
    //用户名
    private String userName;
    //用户编号
    private String userNumber;
    //持有usbWatcher
    private WMIUsbWatcher usbWatcher = new WMIUsbWatcher();
    public FormMain() {
      InitializeComponent();
      initUserConfig();
    }
    /**窗体加载事件中注册usb事件监听
     */
    private void FormMain_Load(object sender, EventArgs e) {
      usbWatcher.AddUSBEventWatcher(USBEventHandler, USBEventHandler,new TimeSpan(0,0,3));
    }
    /**UsbEventHandler
     */
    private void USBEventHandler(Object sender, EventArrivedEventArgs e) {     
      foreach( USBControllerDevice device in WMIUsbWatcher.WhoUSBControllerDevice(e) ) {
        showInfo(device);        
      }
      refreshAndroidDevice();
    }
    /**显示Android设备
     */
    private void refreshAndroidDevice() {
      String result = CommandDo.execute("adb devices");
      //MessageBox.Show(result);
    }

    /**显示Usb设备信息mobile 
     */
    private void showInfo(USBControllerDevice device) {
      //首先清除原有罗列内容
      if(listViewExMobel.Items.Count != 0){
        //listViewExMobel.Clear();----报线程外调用
      }
      //然后添加各个项
      if( listViewExMobel.InvokeRequired ) {
        listViewExMobel.BeginInvoke(new Action<String>((msg) => {
          addItem(device);
        }), device.Antecedent);
      } else {
        addItem(device);
      }
    }

    /**添加Device信息到ListView
     */
    private void addItem(USBControllerDevice device) {
      ListViewItem itm = new ListViewItem();
      itm.Text = device.Antecedent;
      itm.SubItems.Add(device.Dependent);
      listViewExMobel.Items.Add(itm);
    }

    private void button1_Click(object sender, EventArgs e) {
      FormUsb frmUsb = new FormUsb();
      frmUsb.Show();
    }

    private void toolStripButton2_Click(object sender, EventArgs e) {
      FormUsb frmUsb = new FormUsb();
      frmUsb.Show();
    }

    private void superTabControl1_SelectedTabChanged(object sender, DevComponents.DotNetBar.SuperTabStripSelectedTabChangedEventArgs e) {

    }

    private void buttonItem1_Click(object sender, EventArgs e) {
      //styleManager1.ManagerStyle = eStyle.Office2007Black;
      //lblChange.ForeColor = Color.White;
      //String result = CommandDo.execute("adb install -r c:/a.apk",10000);
      //MessageBox.Show(result);

      //CommandDo.execute("adb install -r c:\\a.apk");
      //String cmd = "adb install -r 1.apk";
     // cmd = "cd C:\\Documents and Settings\\DELPHI\\Application Data\\AppKey\\Apps&" + cmd;
     // cmd = cmd.Replace("\\","/");
    //  CommandDo.execute(cmd,0);
      /*String changeDirCmd = "cd C:\\Documents and Settings\\DELPHI\\Application Data\\AppKey\\Apps";
      String installCmd = "adb install -r 1.apk";
      changeDirCmd = changeDirCmd.Replace("\\", "/");
      List<String> cmds = new List<String>();
      cmds.Add(changeDirCmd);
      cmds.Add(installCmd);

      CommandDo.execute(cmds,0);*/

      #region 
      /*Process p = new Process();
      p.StartInfo = new ProcessStartInfo("CMD");

      p.StartInfo.RedirectStandardInput = true;
      p.StartInfo.RedirectStandardOutput = true;
      p.StartInfo.UseShellExecute = false;
      p.Start();

      p.StandardInput.WriteLine("dir");
      p.StandardInput.WriteLine("dir");
      p.StandardInput.WriteLine("exit");
      String s = p.StandardOutput.ReadToEnd();*/
      #endregion

      List<String> cmds = new List<String>();
      String changeDirCmd = "cd C:\\Documents and Settings\\DELPHI\\Application Data\\AppKey\\Apps";
      String installCmd = "adb install -r 1.apk";
      cmds.Add(changeDirCmd);
      cmds.Add("c:");
      cmds.Add(installCmd);

      String str =  CommandDo.execute(cmds,0);
      MessageBox.Show(str);
    }

    private void listViewEx2_SelectedIndexChanged(object sender, EventArgs e) {

    }
    /**窗体关闭事件中移除usb事件监听
     */
    private void FormMain_FormClosing(object sender, FormClosingEventArgs e) {
      usbWatcher.RemoveUSBEventWatcher();
    }

    private void superTabControlPanel2_Click(object sender, EventArgs e) {

    }

    private void superTabControlPanel1_Click(object sender, EventArgs e) {

    }

    private void buttonItem4_Click(object sender, EventArgs e) {
      /*#region
      List<App> apps = new List<App>();
      for( int i = 0; i < 10;i++ ) {
        App app = new App();
        app.setId(""+i);
        app.setName("name"+i);
        app.setDescn("descn"+i);
        app.setVersion("version"+i);

        apps.Add(app);
      }
      #endregion*/
      //AppManager manager = new AppManager();
      //manager.genAppsXml(apps);

      /*List<App> list = manager.getAppsByXml();
      foreach(App a in list){
        ListViewItem itm = new ListViewItem();
        itm.Text = a.getId();
        itm.SubItems.Add(a.getName());
        itm.SubItems.Add(a.getDescn());
        itm.SubItems.Add(a.getVersion());
        listViewExApps.Items.Add(itm);
      } */

 
     

      AppManager appManager = new AppManager();
      List<App> apps = appManager.getAppsByXml(SysUtils.getUserAppAppsXmlPath());
      foreach( App app in apps ) {
        String result = appManager.installApp(app,userName,userNumber);
        MessageBox.Show(result);
      }
      

    }

    private void buttonItem5_Click(object sender, EventArgs e) {
      //Ziper.zip("g:/a", "c:/csb.zip",AppKeyConstants.ZIP_PWD);
      //String userDir = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
      //MessageBox.Show(userDir);


      //textBoxX5.Text =  RsaUtil.RSAEncrypt(AppKeyConstants.RSA_PUBLIC_KEY, textBoxX3.Text);
      //textBoxX4.Text = RsaUtil.RSADecrypt(AppKeyConstants.RSA_PRIVATE_KEY, textBoxX5.Text);

      //实例化打开文件对话框
      OpenFileDialog openFileDlg = new OpenFileDialog();
      //过滤zip文件
      openFileDlg.Filter = "zip files (*.zip)|*.zip" ;
      openFileDlg.CheckFileExists = true;//检查文件是否存在
      openFileDlg.CheckPathExists = true;//检查路径是否存在
      
      //选定文件
      if(openFileDlg.ShowDialog() == DialogResult.OK){
        //使用appManager的导入方法,得到app列表
        AppManager appManager = new AppManager();
        List<App> apps = appManager.importApp(openFileDlg.FileName);
        //迭代app列表,填充listView
        foreach( App app in apps){
          ListViewItem itm = new ListViewItem();
          itm.Text = app.getId();
          itm.SubItems.Add(app.getName());
          itm.SubItems.Add(app.getDescn());
          itm.SubItems.Add(app.getVersion());

          listViewExApps.Items.Add(itm);
        }

        superTabItemAppGame.Focus();
        superTabControlMain.SelectedTabIndex = 1;
      }

    }

    private void colorPickerDropDown2_SelectedColorChanged(object sender, EventArgs e) {
      if (Directory.Exists("c:/sssssssssssssssss")){
        Directory.CreateDirectory("c:/sssssssssssssssss");
      }
      UnZiper.unZip("c:/csb.zip", "c:/sssssssssssssssss", AppKeyConstants.ZIP_PWD);
    }

    private void buttonX2_Click(object sender, EventArgs e) {
      superValidator1.Enabled = false;
    }
    /// <summary>保存用户信息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonSave_Click(object sender, EventArgs e) {
      ///用户名
      String userName = RsaUtil.RSAEncrypt(AppKeyConstants.RSA_PUBLIC_KEY, textBoxUserName.Text);
      ///用户编号
      String userNumber = RsaUtil.RSAEncrypt(AppKeyConstants.RSA_PUBLIC_KEY, textBoxUserNumber.Text);
      ///密码
      String password = RsaUtil.RSAEncrypt(AppKeyConstants.RSA_PUBLIC_KEY, textBoxPassword.Text);
     
      //
      IniUtil iniUtil = new IniUtil(SysUtils.getUserConfigFile());
      iniUtil.WriteString(AppKeyConstants.USER_NAME, AppKeyConstants.USER_NAME, userName);
      iniUtil.WriteString(AppKeyConstants.USER_NUMBER, AppKeyConstants.USER_NUMBER, userNumber);
      iniUtil.WriteString(AppKeyConstants.PASSWORD, AppKeyConstants.PASSWORD, password);
      ///备注
      if( textBoxRemark.Text != "" ) {
        String remark = RsaUtil.RSAEncrypt(AppKeyConstants.RSA_PUBLIC_KEY, textBoxRemark.Text);
        iniUtil.WriteString(AppKeyConstants.REMARK, AppKeyConstants.REMARK,remark);
      }
      
      //textBoxUserNumber.Text = RsaUtil.RSADecrypt(AppKeyConstants.RSA_PRIVATE_KEY ,userName);


    }

    private void initUserConfig(){
      IniUtil iniUtil = new IniUtil(SysUtils.getUserConfigFile());
      userName = RsaUtil.RSADecrypt(AppKeyConstants.RSA_PRIVATE_KEY, iniUtil.ReadString(AppKeyConstants.USER_NAME, AppKeyConstants.USER_NAME, ""));
      textBoxUserName.Text = userName;
      userNumber = RsaUtil.RSADecrypt(AppKeyConstants.RSA_PRIVATE_KEY, iniUtil.ReadString(AppKeyConstants.USER_NUMBER, AppKeyConstants.USER_NUMBER, ""));
      textBoxUserNumber.Text = userNumber;
        
      textBoxPassword.Text =
        RsaUtil.RSADecrypt(AppKeyConstants.RSA_PRIVATE_KEY, iniUtil.ReadString(AppKeyConstants.PASSWORD, AppKeyConstants.PASSWORD, ""));
      textBoxRemark.Text =
        RsaUtil.RSADecrypt(AppKeyConstants.RSA_PRIVATE_KEY, iniUtil.ReadString(AppKeyConstants.REMARK, AppKeyConstants.REMARK, ""));

    }
    /// <summary>
    /// 显示进度条
    /// </summary>
    private void ShowTotalProcessBar() {
      formProgress = new FormProgress();
      // Init increase event
      myIncrease = new IncreaseHandle(formProgress.IncreaseTotal);
      setLable = new SetLable(formProgress.setLable);
      //formProgress.progressCurrent();
      formProgress.ShowDialog();
       
      formProgress = null;
    }
    private void ThreadFun() {


      AppManager appManager = new AppManager();
      List<App> apps = appManager.getAppsByXml(SysUtils.getUserAppAppsXmlPath());
     

      MethodInvoker mi = new MethodInvoker(ShowTotalProcessBar);
      this.BeginInvoke(mi);
      
      Thread.Sleep(1000);//Sleep a while to show window
      
      bool blnIncreased = false;
      object objReturn = null;
      foreach( App app in apps ) {
        String result = appManager.installApp(app, userName, userNumber);
        Invoke(setLable, new Object[] { "正在安装: " + app.getName() });
        
        objReturn = this.Invoke(this.myIncrease,
           new object[] { formProgress.getTotalProgressMaximun()/apps.Count });
        blnIncreased = (bool) objReturn;
        MessageBox.Show(result);
      }
      /*do {
        Thread.Sleep(50);
        objReturn = this.Invoke(this.myIncrease,
            new object[] { 1 });
        blnIncreased = (bool) objReturn;
      }
      while( blnIncreased );*/
    }

    private void buttonItem13_Click(object sender, EventArgs e) {
      Thread thdSub = new Thread(new ThreadStart(ThreadFun));
      thdSub.Start();
    }
  }
}
